import cv2
import numpy as np

class App:
    stact_flag = False
    # 矩形框
    rect = (0,0,0,0)
    stact_X = 0
    stact_Y = 0
    # 鼠标点击事件
    def onmouse(self,event,x,y,flags,param):
        if event == cv2.EVENT_LBUTTONDOWN:
            self.stact_flag = True
            self.stact_X = x
            self.stact_Y = y
            print(self.stact_X,self.stact_Y)
        elif event == cv2.EVENT_LBUTTONUP:
            self.stact_flag = False
            # 画框
            cv2.rectangle(self.img,(self.stact_X,self.stact_Y),(x,y),(0,0,255),2)
            self.rect = (min(self.stact_X,x), min(self.stact_Y,y), abs(self.stact_X-x), abs(self.stact_Y-y))
        elif event == cv2.EVENT_MOUSEMOVE:
            if self.stact_flag == True:
                self.img = self.img2.copy()

                cv2.rectangle(self.img, (self.stact_X, self.stact_Y), (x, y), (255, 0, 0), 2)

    # 操作
    def run(self):
        cv2.namedWindow('input')
        cv2.setMouseCallback('input',self.onmouse)
        self.img = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\yb.jpg")
        # 深拷贝
        self.img2 = self.img.copy()
        self.mask = np.zeros(self.img.shape[:2],np.uint8)
        self.output = np.zeros(self.img.shape,np.uint8)
        while True:
            cv2.imshow('input',self.img)
            cv2.imshow('output',self.output)
            k = cv2.waitKey(100)
            if k == 27:
                break
            if k == ord('q'):
                bgdModel = np.zeros((1, 65), np.float64)
                fgdModel = np.zeros((1, 65), np.float64)
                # 获取背景
                cv2.grabCut(self.img2,self.mask,self.rect,bgdModel,fgdModel,1,cv2.GC_INIT_WITH_RECT)
            # 获取前景
            mask2 = np.where((self.mask==1)|(self.mask==3),255,0).astype('uint8')
            self.output = cv2.bitwise_and(self.img2,self.img2,mask=mask2)

App().run()